<?php if (! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 网站配置 服务
 */

class Setting_service extends MY_Service {

    /**
     * 配置项缓存
     *
     * @var	array
     */
    private static $_settings = array();

    public function __construct() {
        $this->load->model('setting_model');
        $this->get_all();
    }

    /**
     * 获取配置项
     *
     * @param	string	$key
     * @return	bool
     */
    public function get($key) {
        if (isset(self::$_settings[$key])) return self::$_settings[$key];
        $setting = $this->setting_model->get_by(array('key' => $key));
        self::$_settings[$key] = $setting['value'];
        return $setting['value'];
    }

    /**
     * 批量设置配置信息
     *
     * @param array $array 配置信息数组
     *                     $array[] = array('key' => '', 'value' => '', 'description' => '')
     * @return boolean
     */
    public function sets($array) {
        if (empty($array) or ! is_array($array)) return false;

        foreach ($array as $item) {
            $this->set($item['key'], $item['value'], $item['description']);
        }
        return true;
    }

    /**
     * 设置配置项
     *
     * @param	string	$key
     * @param	string	$value
     * @param   string  $description 配置项描述
     * @return	bool
     */
    public function set($key, $value, $description = null) {
        if (! is_string($key)) return false;

        $setting = $this->setting_model->save_setting($key, $value, $description);
        self::$_settings[$key] = $value;
        return true;
    }

    /**
     * 删除配置项
     *
     * @param	string	$key
     * @return	bool
     */
    public function del($key) {
        return $this->setting_model->delete($key);
    }

    /**
     * 获取全部配置项
     *
     * @return	array
     */
    public function get_all() {
        if (self::$_settings) return self::$_settings;

        $settings = $this->setting_model->get_all();
        foreach ($settings as $setting) {
            $value = $setting['type'] == 'string' ? $setting['value'] : unserialize($setting['value']);
            self::$_settings[$setting['key']] = $value;
        }
        return self::$_settings;
    }
}

/* End of file setting_service.php */
/* Location: ./application/service/setting/setting_service.php */
